package category

import (
	"gin_demo/internal/consts"
	"gin_demo/internal/model"
	"gin_demo/utility"
	"time"

	"github.com/gin-gonic/gin"
)

func List(ctx *gin.Context, req PageListReq) {
	// 分页查询
	list := []model.Category{}
	var Count int64
	tx := consts.App.DB.Limit(req.Limit).Offset(req.Page - 1).Find(&list).Count(&Count)
	if tx.Error != nil {
		consts.App.Log.Error(tx.Error.Error())
		utility.Fail(ctx, "分类数据加载失败")
	} else {
		info := CategoryRes{
			Count: Count,
			List:  list,
		}
		utility.Success(ctx, info)
	}
}

func Create(ctx *gin.Context, req AddCategoryReq) {
	// 分页添加
	list := model.Category{
		ParentId: req.ParentId,
		PicUrl:   req.PicUrl,
		Name:     req.Name,
		Sort:     req.Sort,
		Level:    req.Level,
	}
	tx := consts.App.DB.Create(&list)
	if tx.Error != nil {
		consts.App.Log.Error(tx.Error.Error())
		utility.Fail(ctx, "分类数据添加失败")
	} else {
		utility.Success(ctx, list)
	}
}

func Delete(ctx *gin.Context, req SoftDeleteReq) {
	// 分页删除
	list := model.Category{}

	tx := consts.App.DB.Model(&list).Where("id=?", req.Id).Update("deleted_at", time.Now())
	if tx.Error != nil {
		consts.App.Log.Error(tx.Error.Error())
		utility.Fail(ctx, "分类数据删除失败")
	} else {
		utility.Success(ctx, "分类数据删除成功")
	}
}

func Update(ctx *gin.Context, req UpdateCategoryReq) {
	// 分页删除
	list := model.Category{
		Name:     req.Name,
		ParentId: req.ParentId,
		PicUrl:   req.PicUrl,
		Level:    req.Level,
		Sort:     req.Sort,
	}

	tx := consts.App.DB.Model(&list).Where("id=?", req.Id).Updates(&list)
	if tx.Error != nil {
		consts.App.Log.Error(tx.Error.Error())
		utility.Fail(ctx, "分类数据更新失败")
	} else {
		utility.Success(ctx, list)
	}
}
